package 矩阵;

import java.util.Random;

public class 矩阵相乘 {

    public static void main(String[] args) {
        int rowA = 6,cloumA = 8;
        int[][] matrixA = creatMatrix(rowA,cloumA);
        showMatrix(matrixA);
        int rowB = 8,cloumB = 5;
        int[][] matrixB = creatMatrix(rowB,cloumB);
        showMatrix(matrixB);
        int[][] matrixC = multiplication_Matrix(matrixA,matrixB);
        showMatrix(matrixC);
    }

    static int[][] creatMatrix(int row, int column){
        Random random = new Random();  // 随机函数，默认当前时间为种子
        int[][] matrix = new int[row][column];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                matrix[i][j] = random.nextInt(10); // 范围 0-99
            }
        }
        return matrix;
    }
    static int[][] multiplication_Matrix(int[][] matrixA,int[][] matrixB){
        //二维数组本质是一维数组，行数=数组名.length,列数=数组名[0].length; 矩阵乘法，前提columnA == rowB;
        int rowA = matrixA.length, columnA = matrixA[0].length;
        int rowB = matrixB.length, columnB = matrixB[0].length;
        int[][] multiplicationMatrix = new int[rowA][columnB];
        if(columnA != rowB) {
            System.out.println("错误，违反矩阵相乘法则");
            return multiplicationMatrix;
        }
        for (int i = 0; i < rowA; i++) {            // m*n n*u
            for (int j = 0; j < columnB; j++) {     // 外积定型  内积定否
                multiplicationMatrix[i][j] = 0;
                for (int k = 0; k < columnA; k++) { // kw为: A的列，B的行
                    multiplicationMatrix[i][j] = multiplicationMatrix[i][j] + matrixA[i][k]*matrixB[k][j];
                }
            }
        }
        return multiplicationMatrix;
    }
    static void showMatrix(int[][] matrix){
        int row = matrix.length;
        int column = matrix[0].length;

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                System.out.print(matrix[i][j]+"\t");
            }
            System.out.println();
        }
        System.out.println();
    }
}
